package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.FillInInfo;
import cn.com.hhrcw.mapstruct.FillInInfoConvert;
import cn.com.hhrcw.params.FillInInfoParams;
import cn.com.hhrcw.service.IFillInInfoService;
import cn.com.hhrcw.utils.ExcelUtil;
import cn.com.hhrcw.utils.ProvinceCityCountyUtils;
import cn.com.hhrcw.vo.FillInInfoVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 * @ClassName FillInInfoController采集信息控制类
 * @Description
 * @Author duchao
 * @Date 2023/4/9 20:41
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/admin/fillInInfo")
@Api(tags = "信息采集Controller")
@Validated
public class FillInInfoController extends JeecgController<FillInInfo, IFillInInfoService> {
    @Autowired
    private IFillInInfoService iFillInInfoService;

    @Autowired
    private FillInInfoConvert fillInInfoConvert;

    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 信息采集保存
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("信息采集保存-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid FillInInfoParams params) {
        FillInInfo fillInInfo = fillInInfoConvert.toEntity(params);
        fillInInfo.setId(IdUtil.fastSimpleUUID());
        fillInInfo.setCreateTime(DateUtil.date());
        boolean saved = iFillInInfoService.saveOrUpdate(fillInInfo);
        return saved ? Result.ok() : Result.error("添加失败");
    }
    /**
     * 获取信息采集数量
     *
     * @return
     */
    @PostMapping(value = "/getFillInInfoList")
    @AutoLog("信息采集-查询(姓名+手机号+场次号)")
    @ApiOperation(value = "查询", notes = "查询")
    public Result<List<FillInInfo>> getList(@RequestBody @Valid FillInInfoParams params, HttpServletRequest request) {
        List<FillInInfo> fillInInfoList = iFillInInfoService.lambdaQuery()
                .eq(FillInInfo::getUsername, params.getUsername())
                .eq(FillInInfo::getPhone, params.getPhone())
                .eq(FillInInfo::getRecruitSessions, params.getRecruitSessions()).list();
        if (fillInInfoList.size() < 1) {
            fillInInfoList = new ArrayList<FillInInfo>();
        }
        return Result.ok(fillInInfoList);
    }

    /**
     * 获取信息采集数量
     *
     * @return
     */
    @PostMapping(value = "/getFillInInfoByChannelList")
    @AutoLog("信息采集-查询(姓名+手机号+渠道号)")
    @ApiOperation(value = "查询", notes = "查询")
    public Result<List<FillInInfo>> getFillInInfoByChannelList(@RequestBody @Valid FillInInfoParams params, HttpServletRequest request) {
        List<FillInInfo> fillInInfoList = iFillInInfoService.lambdaQuery()
                .eq(FillInInfo::getUsername, params.getUsername())
                .eq(FillInInfo::getPhone, params.getPhone())
                .eq(FillInInfo::getChannel, params.getChannel()).list();
        if (fillInInfoList.size() < 1) {
            fillInInfoList = new ArrayList<FillInInfo>();
        }
        return Result.ok(fillInInfoList);
    }
    /**
     * 信息采集数据统计
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(value = "信息采集数据统计",logType = 2,ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    @PermissionData
    public Result<Page<FillInInfo>> list(FillInInfoParams params, HttpServletRequest request) {
        LambdaQueryWrapper<FillInInfo> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(params.getUsername())) {
            queryWrapper.like(FillInInfo::getUsername, params.getUsername());
        }
        queryWrapper.orderByDesc(FillInInfo::getCreateTime);

        IPage<FillInInfo> page = service.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<FillInInfo, FillInInfoVO> fun = statisticsFillInInfo-> fillInInfoConvert.toVO(statisticsFillInInfo);

        return Result.ok((Page) page.convert(fun));
    }
    /**
     * 导出excel
     *
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public void exportXls(HttpServletResponse response, FillInInfoParams params) {
        LambdaQueryWrapper<FillInInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(params.getUsername())) {
            queryWrapper.like(FillInInfo::getUsername, params.getUsername());
        }
        queryWrapper.orderByDesc(FillInInfo::getCreateTime);
        List<FillInInfo> data = service.list(queryWrapper);
        ExcelUtil<FillInInfoVO> excelUtil = new ExcelUtil();
        if (!CollectionUtils.isEmpty(data)) {
            data.forEach(opJob -> {
                //转译籍贯
                if(opJob.getBirthPlace() != null && !"null".equals(opJob.getBirthPlace())){
                    opJob.setBirthPlace(getTransNames("sys_area", opJob.getBirthPlace(), "id", "name"));
                }
            });
        }
        excelUtil.setClose(false);
        excelUtil.buildExcel(response, fillInInfoConvert.toVO(data));
    }
    /*
     * 根据字典转译籍贯
     */
    public String getTransNames(String table, String code, String column, String columnValue) {
        try {
            StringBuilder sql = new StringBuilder("select " + columnValue + " from `" + table + "` where " + column + " in (");
            for (String c : code.split(",")) {
                sql.append("'" + c + "',");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
            List<String> value = jdbcTemplate.queryForList(sql.toString(), String.class);
            return ProvinceCityCountyUtils.getProvinceCityCountyShort(value);
        } catch (Exception e) {
            return "";
        }
    }
}
